<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" :width="lang === 'zh'?'620px':'675px'" top='5vh' @close='close'>
    <div class="dialogContentBoxMaxHeight90">
      <el-form ref="form" :model="record" label-width="105px" inline :rules="rules" label-position="left" style="margin:0 20px;">
        <el-form-item :label="$t('策略名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref="recordName" style="width:217px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('IP类型')" prop="ip_type">
          <el-radio-group v-model="record.ip_type" style="width:200px;">
            <el-radio class="ipType" label="ipv4">IPv4</el-radio>
            <el-radio class="ipv" label="ipv6">IPv6</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('源IP')" prop="src">
          <el-select v-model="record.src" ref="recordSrc" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="item in filMac(sipList)" :key="item.id" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
          <addr-dialog @commandList='commandList' :nameType='"src"'></addr-dialog>
        </el-form-item>
        <el-form-item :label="$t('目的IP')" prop="dst">
          <el-select v-model="record.dst" ref="recordDst" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="item in filMac(dipList)" :key="item.id" :label="item.nameShow" :value="item.name">
            </el-option>
          </el-select>
          <addr-dialog @commandList='commandList' :nameType='"dst"'></addr-dialog>
        </el-form-item>
        <el-form-item :label="$t('应用')" prop="app">
          <el-select v-model="record.app" ref="recordApp" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="item in appList" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <AppDialog @appDataList='appDataList'></AppDialog>
        </el-form-item>
        <el-form-item :label="$t('服务')" prop="service">
          <el-select v-model="record.service" ref="service" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="item in iservicepsList" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <ServerDialog @serviceList='serviceList'></ServerDialog>
        </el-form-item>
        <el-form-item :label="$t('用户')" prop="user">
          <el-select v-model="record.user" ref="user" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="item in userList" :key="item.name" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <el-button type="primary" plain size='small' style="margin-left:10px" @click="userDialogVisible">{{$t('新建用户')}}</el-button>
          <el-button type="primary" plain size='small' @click="groupDialogVisible">{{$t('新建用户组')}}</el-button>
          <group-dialog v-if="groupDialog" ref="refGroupDialogVisible" @userListData='userListData'></group-dialog>
          <user-dialog v-if="userDialog" ref="refUserDialogVisible" @userListData='userListData'></user-dialog>
        </el-form-item>
        <el-form-item :label="$t('时间')" prop="time">
          <el-select v-model="record.time" ref="recordTime" :placeholder="$t('请选择')" size='small' filterable clearable>
            <el-option v-for="item in timeList" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
          <TimeDialog @timeDataList='timeDataList'></TimeDialog>
        </el-form-item>
        <el-form-item :label="$t('告警')" prop="enable" class="flowDialogSwitch" style="width:400px;">
          <el-switch :width="lang === 'zh'?60:70" v-model="enable" class="enable switch" active-color="#009966" inactive-color="#CCCCCC" @change="enableChange" :active-value="true" :inactive-value="false" :active-text="$t('启用')" :inactive-text="$t('禁用')"></el-switch>
        </el-form-item>
        <el-form-item :label="$t('告警阀值')" prop="threshold">
          <el-input v-emoji v-model="record.threshold" ref="threshold" :disabled='!enable' style="width:217px;" size='small'></el-input>
        </el-form-item>
        <el-form-item label="" prop="thresholds">
          <el-select v-model="record.thresholds" ref="thresholds" :disabled='!enable' style="width:100px;" size='small' filterable>
            <el-option v-for="item in thresholdsList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addInfo, editInfo } from '@/api/network/flow'
import { getAddrGroupArray } from '@/api/list/addr-group'
import { getAddrArray } from '@/api/list/addr'
import { getServiceArray, getServiceReArray } from '@/api/list/server'
import { getTimeArray } from '@/api/list/time'
import { getAppArray, getAppReArray } from '@/api/list/app'
import { getGroupUserInfo, getUserArray } from '@/api/user/user'
// import { getAssetArray } from '@/api/list/assets/assetobject'
// import { getAssetGroupArray } from '@/api/list/assets/assetGroup'
import addrDialog from './AddrDialog'
import ServerDialog from './ServerDialog'
import TimeDialog from './TimeDialog'
import AppDialog from './AppDialog'
import GroupDialog from './userTools/GroupDialog'
import UserDialog from './userTools/UserDialog'
import { inputClass, selectClass } from '@/utils/input-class.js'

export default {
  name: 'FlowDialog',
  components: {
    addrDialog,
    ServerDialog,
    TimeDialog,
    AppDialog,
    GroupDialog,
    UserDialog
  },
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('请输入名称')))
      } else {
        callback()
      }
    }
    var validateThreshold = (rule, value, callback) => {
      if (this.enable === true) {
        if (!String(value).trim()) {
          callback(new Error(this.$t('请输入告警阀值')))
        } else if (Number(value) < 1) {
          callback(new Error(this.$t('不能输入小于1的数字')))
        } else if (!this.isInteger(value)) {
          callback(new Error(this.$t('只能输入整数')))
        } else if (this.record.thresholds === 'B' && Number(this.record.threshold) > 4294967295) {
          callback(new Error(this.$t('告警阀值不得大于4294967295B')))
        } else if (this.record.thresholds === 'KB' && Number(this.record.threshold) > 4194303) {
          callback(new Error(this.$t('告警阀值不得大于4194303KB')))
        } else if (this.record.thresholds === 'M' && Number(this.record.threshold) > 4095) {
          callback(new Error(this.$t('告警阀值不得大于4095M')))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      userDialog: false,
      groupDialog: false,
      record: {
        id: null,
        name: '',
        type: '',
        ip_type: 'ipv4',
        src: '',
        dst: '',
        service: '',
        app: '',
        user: '',
        time: '',
        threshold: '',
        thresholds: 'KB'
      },
      recordCopy: {
        id: null,
        name: '',
        type: '',
        ip_type: 'ipv4',
        src: '',
        dst: '',
        service: '',
        app: '',
        user: '',
        time: '',
        threshold: '',
        thresholds: 'KB'
      },
      enable: false,
      sipList: [],
      dipList: [],
      userList: [],
      iservicepsList: [],
      appList: [],
      timeList: [],
      thresholdsList: ['B', 'KB', 'M'],
      lang: this.$i18n.locale,
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        threshold: [{ required: false, validator: validateThreshold, trigger: 'blur' }]
      }
    }
  },
  methods: {
    filMac(list=[]) { 
      return list.filter(item => item.ip_type !== 7) 
    },
    init (data, type) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['recordName', 'threshold']
        const selectData = ['recordSrc', 'recordDst', 'recordApp', 'service', 'user', 'recordTime', 'thresholds']
        inputClass(this.$refs, data)
        selectClass(this.$refs, selectData)
      })
      this.record.type = type
      if (data) {
        this.record = Object.assign(this.record, data)
        this.enable = data.threshold !== 0
        if ((data.threshold % (1024 * 1024)) === 0 && (data.threshold % (1024 * 1024)) !== data.threshold) {
          this.record.threshold = this.record.threshold / 1024 / 1024
          this.record.thresholds = 'M'
        } else if ((data.threshold % 1024) === 0 && (data.threshold % 1024) !== data.threshold) {
          this.record.threshold = data.threshold / 1024
          this.record.thresholds = 'KB'
        } else {
          this.record.thresholds = 'B'
        }
      }
      this.commandList()
      this.serviceList()
      this.timeDataList()
      this.appDataList()
      this.userListData()
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var formData = JSON.parse(JSON.stringify(this.record))
          if (this.enable) {
            formData.threshold = formData.thresholds === 'B' ? formData.threshold : (formData.thresholds === 'KB' ? (formData.threshold * 1024) : (formData.threshold * 1024 * 1024))
          } else {
            formData.threshold = 0
          }
          if (!this.record.id) {
            this.$refs.form.validate((valid) => {
              if (valid) {
                addInfo(formData).then(res => {
                  if (res.status === 0) {
                    this.$message({
                      message: this.$t('添加成功'),
                      type: 'success'
                    })
                    this.close()
                    this.$parent.listData()
                  }
                })
              }
            })
          } else {
            this.$refs.form.validate((valid) => {
              if (valid) {
                editInfo(formData).then(res => {
                  if (res.status === 0) {
                    this.$message({
                      message: this.$t('编辑成功'),
                      type: 'success'
                    })
                    this.close()
                    this.$parent.listData()
                  }
                })
              }
            })
          }
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.enable = false
      this.sipList = []
      this.dipList = []
      this.userList = []
      this.iservicepsList = []
      this.appList = []
      this.timeList = []
      this.$refs.form.resetFields()
    },
    enableChange () {
      this.$refs['form'].clearValidate('threshold')
    },
    userDialogVisible () {
      this.userDialog = true
      this.$nextTick(() => {
        this.$refs.refUserDialogVisible.init()
      })
    },
    groupDialogVisible () {
      this.groupDialog = true
      this.$nextTick(() => {
        this.$refs.refGroupDialogVisible.init()
      })
    },
    commandList (data, nameType, name) {
      this.sipList = []
      this.dipList = []
      getAddrArray().then(response => {
        if (response.status === 0) {
          getAddrGroupArray().then(res => {
            if (res.status === 0) {
              // this.dipList = response.info.concat(res.info)
              // getAssetArray().then(resAsset => {
              //   if (resAsset.status === 0) {
              //     getAssetGroupArray().then(resAssetGroup => {
              //       if (resAssetGroup.status === 0) {
              for (let item of response.info) {
                item.nameShow = this.$t('地址-') + item.name
                this.sipList.push(item)
                this.dipList.push(item)
              }
              for (let item of res.info) {
                item.nameShow = this.$t('地址组-') + item.name
                this.sipList.push(item)
                this.dipList.push(item)
              }
              // for (let item of resAsset.info) {
              //   item.nameShow = '资产对象-' + item.name
              //   this.sipList.push(item)
              //   this.dipList.push(item)
              // }
              // for (let item of resAssetGroup.info) {
              //   item.nameShow = '资产组-' + item.name
              //   this.sipList.push(item)
              //   this.dipList.push(item)
              // }
              //       }
              //     })
              //   }
              // })
            }
          })
        }
      })
      if (data && nameType === 'src') {
        this.record.src = name
      } else if (data && nameType === 'dst') {
        this.record.dst = name
      }
    },
    serviceList (data) {
      this.iservicepsList = []
      getServiceArray().then(response => {
        if (response.status === 0) {
          getServiceReArray().then(res => {
            if (res.status === 0) {
              this.iservicepsList = response.info.concat(res.info)
            }
          })
        }
      })
      if (data) {
        this.record.service = data.name
      }
    },
    timeDataList (data) {
      this.timeList = []
      getTimeArray().then(response => {
        if (response.status === 0) {
          this.timeList = response.info
        }
      })
      if (data) {
        this.record.time = data.name
      }
    },
    appDataList (data, appType) {
      this.appList = []
      getAppArray().then(response => {
        if (response.status === 0) {
          getAppReArray().then(res => {
            if (res.status === 0) {
              this.appList = response.info.concat(res.info)
            }
          })
        }
      })
      if (data) {
        this.record.app = data.name
      }
    },
    userListData (name) {
      getGroupUserInfo({ name: 'root' }).then(res => {
        if (res.status === 0) {
          getUserArray().then(response => {
            if (response.status === 0) {
              var groupList = response.info
              groupList.splice(0, 1)
              this.userList = res.info.concat(groupList)
              if (name) {
                this.record.user = name
              }
            }
          })
        }
      })
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    }
  }
}
</script>
